package game.module.hall.logic;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import game.HallServer;
import game.entity.PlayingRole;
import game.module.ddz.logic.DdzDataManager;
import game.module.mj.logic.MjDataManager;
import game.module.nn.logic.NnDataManager;
import game.module.qzmj.logic.QzmjDataManager;
import game.module.sss.logic.SssDataManager;
import game.session.SessionManager;
import lua.LuaMessageHall.PushAutoJoinRoom;

public class HallManager {

	private static Logger logger = LoggerFactory.getLogger(HallManager.class);

	static class SingletonHolder {
		static HallManager instance = new HallManager();
	}

	public static HallManager getInstance() {
		return SingletonHolder.instance;
	}

	public void roomTypeBack(int opType, int playerId, int roomType,long sessionId) {
		if (roomType != -1) {
			PlayingRole pr = SessionManager.getInstance().getPlayer(playerId);
			if (pr != null && pr.isChannelActive()) {
				String room_server_host = HallServer.getInstance().getServerConfig().getRsSocketHost();
				int room_server_port = HallServer.getInstance().getServerConfig().getRsSocketPort();
				PushAutoJoinRoom pushMsg = new PushAutoJoinRoom(room_server_port,sessionId, room_server_host, (byte) roomType,
						(byte) 2);
				pr.writeAndFlush(pushMsg.build(pr.alloc()));
			}
		}
	}

	public void checkHallRoomType(PlayingRole playingRole) {
		int playerId = playingRole.getId();
		int hallRoomType = -1;
		if (DdzDataManager.getInstance().isPlayerInRoom(playerId)) {
			hallRoomType = 1;
		} else if (NnDataManager.getInstance().isPlayerInRoom(playerId)) {
			hallRoomType = 2;
		} else if (SssDataManager.getInstance().isPlayerInRoom(playerId)) {
			hallRoomType = 3;
		} else if (MjDataManager.getInstance().isPlayerInRoom(playerId)) {
			hallRoomType = 4;
		} else if(QzmjDataManager.getInstance().isPlayerInRoom(playerId)) {
			hallRoomType = 5;
		}
		if (hallRoomType > 0) {
			PushAutoJoinRoom pushMsg = new PushAutoJoinRoom(0,0, "", (byte) hallRoomType, (byte) 1);
			if (playingRole != null && playingRole.isChannelActive()) {
				playingRole.writeAndFlush(pushMsg.build(playingRole.alloc()));
			}
		} else {// 检索房间服务器
			String rsLanHost = HallServer.getInstance().getServerConfig().getRsLanHost();
			int rsLanPort = HallServer.getInstance().getServerConfig().getRsLanPort();
			boolean reconnectRet = HallServer.getInstance().getLanClientManager().connect(rsLanHost, rsLanPort);
			if (reconnectRet) {
				HallServer.getInstance().getLanClientManager().sendCheckRoomType2Rs(rsLanHost, rsLanPort, playerId, 1);
			} else {
				logger.error("connect 2 roomServer error!rsLanHost={},rsLanPort={}", rsLanHost, rsLanPort);
			}
		}
	}

}
